{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8662e6c7-d290-4422-bd49-500b84fffee7",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.preprocessing import MinMaxScaler\n",
    "import tensorflow as tf\n",
    "\n",
    "\n",
    "class NN(object):\n",
    "    def __init__(self):\n",
    "        self.df = pd.read_csv('NN/scenic_data.csv')\n",
    "\n",
    "    def create_dataset(self, data, n_steps):\n",
    "        \"\"\"构造数据\"\"\"\n",
    "        X, y = [], []\n",
    "        for i in range(len(data) - n_steps):\n",
    "            X.append(data[i:i + n_steps])\n",
    "            y.append(data[i + n_steps, :18])\n",
    "        return np.array(X), np.array(y)\n",
    "\n",
    "    def get_model(self):\n",
    "        n_steps = 7  # 长度7天\n",
    "        data = self.df.values\n",
    "        X, y = self.create_dataset(data, n_steps)\n",
    "\n",
    "        # 训练集与测试集划分\n",
    "        train_size = int(len(X) * 0.8)\n",
    "        X_train, X_test = X[:train_size], X[train_size:]\n",
    "        y_train, y_test = y[:train_size], y[train_size:]\n",
    "\n",
    "        model = tf.keras.models.Sequential()\n",
    "        model.add(tf.keras.layers.LSTM(50, activation='relu', return_sequences=True, input_shape=(n_steps, )))\n",
    "        model.add(tf.keras.layers.LSTM(50, activation='relu'))\n",
    "        model.add(tf.keras.layers.Dense(18))\n",
    "        model.compile(optimizer='adam', loss='mse')\n",
    "        model.fit(X_train, y_train, epochs=50, validation_data=(X_test, y_test))\n",
    "\n",
    "        # 评估\n",
    "        loss = model.evaluate(X_test, y_test)\n",
    "        print(f\"测试集损失: {loss:}\")\n",
    "\n",
    "        # 保存模型\n",
    "        tf.keras.models.save_model(model, 'NN/my_model.keras')\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    nn = NN()\n",
    "    nn.get_model()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
